package common;


import java.security.MessageDigest;

/**
 * 字符串加密类，支持MD5、SHA-1和SHA-256算法；
 * 
 * @author huojun 2008年3月30日
 */
public class StringSecurity {

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	public final static String MD5 = "MD5";
	public final static String SHA1 = "SHA-1";
	public final static String SHA256 = "SHA-256";

	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * 数据加密，默认使用MD5算法
	 * 
	 * @param data
	 *            原始数据
	 * @return 密文
	 */
	public static String encode(String data) {
		String resultString = null;
		try {
			resultString = new String(data);
			MessageDigest md = MessageDigest.getInstance(MD5);
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes("UTF-8")));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString.toUpperCase();
	}

	/**
	 * 数据加密
	 * 
	 * @param data
	 *            原始数据
	 * @param encType
	 *            加密类型
	 * @return 密文
	 */
	public static String encode(String data, String encType) {
		String resultString = null;
		try {
			resultString = new String(data);
			MessageDigest md = MessageDigest.getInstance(encType);
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString.toUpperCase();
	}

	public static void main(String[] args) {
		// String str =
		// "callback=thread.getcomments&params=[\"307489\"]&c5604b3f24794d9ca96c7f938423b922";
		// System.out
		// .println("callback=thread.getcomments&params=[\"307489\"]&sign="
		// + encode(str));
		String md5Pwd = StringSecurity.encode("111111");
		System.out.println(md5Pwd);
	}
}
